package com.miniprogram.api.advice;

import com.miniprogram.common.dto.ResponseVo;
import com.miniprogram.common.enums.RestStatusEnum;
import com.miniprogram.common.exception.RestException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.lang.reflect.UndeclaredThrowableException;

/**
 * 异常处理公用方法
 *
 * @author lin
 * @since 2019年11月16日
 */
@RestControllerAdvice
@Slf4j
public class ExceptionHandleController {

    /**
     * 异常处理切面
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseVo<String> handleHope(Throwable e) {
        if (e instanceof RestException) {
            RestException re = (RestException) e;
            log.error(re.getRestStatusEnum().value(), e);
            if (RestStatusEnum.OTHER.code().equals(re.getRestStatusEnum().code())) {
                return new ResponseVo<>(((RestException) e).getRestStatusEnum(), re.getMessage());
            } else {
                return new ResponseVo<>(((RestException) e).getRestStatusEnum());
            }
        } else if (e instanceof AuthorizationException) {
            if (e.getMessage().contains("does not have role")) {
                return new ResponseVo<>(RestStatusEnum.FORBIDDEN);
            } else {
                return new ResponseVo<>(RestStatusEnum.UNAUTHORIZED);
            }
        } else if (e instanceof UndeclaredThrowableException) {
            e = ((UndeclaredThrowableException) e).getUndeclaredThrowable();
            log.error("服务器出现错误", e);
            new ResponseVo<String>(RestStatusEnum.ERROR);
        }
        if (e != null && e.getMessage() != null && e.getMessage().contains("uindex")) {
            return new ResponseVo<>(RestStatusEnum.ERROR, "输入的数据已存在");
        }
        log.error("服务器出现错误", e);
        return new ResponseVo<>(RestStatusEnum.ERROR);
    }

}